package com.security.test.handle;

import com.alibaba.fastjson2.JSON;
import com.security.test.common.R;
import com.security.test.entity.MyUserDetail;
import com.security.test.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class MyLogoutHandler implements LogoutSuccessHandler {

    @Autowired
    private RedisService redisService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.OK.value());
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            try {
                MyUserDetail myUser = (MyUserDetail) authentication.getDetails();
                // 移除token
                redisService.deleteObject(myUser.getToken());
                // 组装对客户端响应信息
//                ServerResponse<String> serverResponse = ServerResponse.createBySuccess("注销成功");

                // 响应给客户端
                response.getWriter().write(JSON.toJSONString(R.ok("注销成功")));
            } catch (Exception e) {
                // 组装对客户端响应信息
                log.error("销毁用户口令异常", e);
                // 响应给客户端
                response.getWriter().write(JSON.toJSONString(R.fail("登录失败，销毁用户口令失败")));
            }
        }

    }
}
